<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item label="角色" prop="roleIds">
          <Role v-model="obj.roleIds" keyName="id" keyShow="roleName" placeholder="角色" title="角色查询" />
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input v-model="listQuery.username" placeholder="用户名" @keyup.enter="handleFilter" />
        </el-form-item>
        <!--
        <el-form-item prop="password" label="密码">
          <el-input v-model="listQuery.password" placeholder="密码" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="state" label="状态">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('UserState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-radio-group v-model="listQuery.gender">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('UserGender')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!--
        <el-form-item prop="needModify" label="是否强制修改密码">
          <el-input v-model="listQuery.needModify" placeholder="是否强制修改密码" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item label="最后一次登录时间">
          <el-date-picker v-model="listQuery.lastLoginTimeRange"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          style="width: 380px"
                          type="datetimerange"
                          range-separator="-"
                          start-placeholder="最后一次登录时间开始"
                          end-placeholder="最后一次登录时间结束" />
        </el-form-item>
        <el-form-item prop="lastLoginIp" label="最后一次登录IP">
          <el-input v-model="listQuery.lastLoginIp" placeholder="最后一次登录IP" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input v-model="listQuery.name" placeholder="姓名" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="mobile" label="手机号码">
          <el-input v-model="listQuery.mobile" placeholder="手机号码" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="idcard" label="身份证号">
          <el-input v-model="listQuery.idcard" placeholder="身份证号" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="listQuery.email" placeholder="邮箱" @keyup.enter="handleFilter" />
        </el-form-item>
        <!--
        <el-form-item prop="organizationId" label="组织架构ID">
          <el-input v-model="listQuery.organizationId" placeholder="组织架构ID" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="rank" label="职级">
          <el-select v-model="listQuery.rank" class="m-2" placeholder="请选择">
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getDictList('UserRank')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
          <el-button v-show="checkAuthByCode('PD0011')" type="primary" icon="Edit" @click="handleAdd">
            新增
          </el-button>
          <el-button v-show="checkAuthByCode('PD0014')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="用户名" prop="username" min-width="150px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.username }}</template>
      </el-table-column>
      <el-table-column align="center" label="密码" prop="password" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">******</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state" min-width="160px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <el-switch v-model="row.state"
                     active-value="1"
                     active-text="启用"
                     inactive-value="0"
                     inactive-text="禁用"
                     @change="handleModifyStatus(row)"
                     :disabled="!checkAuthByCode('PD0012')" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名" prop="name" min-width="100px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="性别" prop="gender" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('UserGender')" :enum-key="row.gender" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="组织架构" prop="organizationId" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreignIds="row.organizationId" :foreignLabel="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="角色" prop="mobile" min-width="260px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <LabelTag :foreignList="roleList" :foreignIds="row.roleIds.join(',')" :foreignLabel="'roleName'" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号码" prop="mobile" min-width="105px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="身份证号" prop="idcard" min-width="105px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="邮箱" prop="email" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.email }}</template>
      </el-table-column>
      <el-table-column align="center" label="是否强制修改密码" prop="needModify" min-width="205px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('CommonYesNo')" :enum-key="row.needModify" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后一次登录时间" prop="lastLoginTime" min-width="160px" sortable>
        <template v-slot="{row}"><DateTag :timestamp="row.lastLoginTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后一次登录IP" prop="lastLoginIp" min-width="160px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.lastLoginIp }}</template>
      </el-table-column>
      <el-table-column align="center" label="职级" prop="rank" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <DictTag :dict-list="getDictList('UserRank')" :dict-key="row.rank" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('PD0012')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('PD0013')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="obj.username" placeholder="请输入用户名，最多输入30个字符" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="obj.password" type="password" placeholder="请输入密码，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-switch v-model="obj.state" active-value="1" active-text="启用" inactive-value="0" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="是否强制修改密码" prop="needModify">
          <el-switch v-model="obj.needModify" active-value="1" active-text="是" inactive-value="0" inactive-text="否" />
        </el-form-item>
        <el-form-item label="最后一次登录时间" prop="lastLoginTime" v-if="dialogType === 'view'">
          <el-date-picker v-model="obj.lastLoginTime" placeholder="" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="最后一次登录IP" prop="lastLoginIp" v-if="dialogType === 'view'">
          <el-input v-model="obj.lastLoginIp" placeholder="=" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="obj.name" placeholder="请输入姓名，最多输入20个字符" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="obj.gender">
            <el-radio-button v-for="item in getEnumList('UserGender')" :label="item.key">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="obj.mobile" placeholder="请输入手机号码，最多输入15个字符" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idcard">
          <el-input v-model="obj.idcard" placeholder="请输入身份证号，最多输入18个字符" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="obj.email" placeholder="请输入邮箱，最多输入50个字符" />
        </el-form-item>
        <el-form-item label="职级" prop="rank">
          <el-select v-model="obj.rank" class="m-2" placeholder="请选择">
            <el-option v-for="item in getDictList('UserRank')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属组织架构" prop="organizationId">
          <Organization v-model="obj.organizationId" keyName="id" keyShow="organizationName" placeholder="所属组织架构" title="部门查询" />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox-group v-model="roleCheckedList">
            <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{item.roleCode}} - {{item.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess, initListUpdate} from "@/config/common";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'
import Role from "@/views/components/base/selectRole.vue";

const emptyObj = {
  username: null, // 用户名
  password: null, // 密码
  state: '1', // 状态
  needModify: '1', // 是否强制修改密码
  lastLoginTime: null, // 最后一次登录时间
  lastLoginIp: null, // 最后一次登录IP
  name: null, // 姓名
  gender: null, // 性别
  mobile: null, // 手机号码
  idcard: null, // 身份证号
  email: null, // 邮箱
  organizationId: null, // 组织架构ID
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null
}

export default {
  name: 'user_nocache',
  components: {Organization, Role},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        username: null,
        password: null,
        state: null,
        needModify: null,
        lastLoginTimeStart: null,
        lastLoginTimeEnd: null,
        lastLoginTimeRange: [], //
        lastLoginIp: null,
        name: null,
        gender: null,
        mobile: null,
        idcard: null,
        email: null,
        organizationId: null,
        rank: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        username: [{ required: true, validator: customValidator, min: 1, max: 30, label: '用户名', trigger: ['blur', 'change'] }],
        password: [{ required: true, validator: customValidator, min: 1, max: 100, label: '密码', trigger: ['blur', 'change'] }],
        state: [{ required: true, validator: customValidator, min: 1, max: 20, label: '状态', trigger: ['blur', 'change'] }],
        needModify: [{ required: false, validator: customValidator, min: 0, max: 20, label: '是否强制修改密码', trigger: ['blur', 'change'] }],
        lastLoginTime: [{ required: false, validator: customValidator, min: 0, max: 0, label: '最后一次登录时间', trigger: ['blur', 'change'] }],
        lastLoginIp: [{ required: false, validator: customValidator, min: 0, max: 15, label: '最后一次登录IP', trigger: ['blur', 'change'] }],
        name: [{ required: true, validator: customValidator, min: 0, max: 20, label: '姓名', trigger: ['blur', 'change'] }],
        gender: [{ required: false, validator: customValidator, min: 0, max: 20, label: '性别', trigger: ['blur', 'change'] }],
        mobile: [{ required: false, validator: customValidator, min: 0, max: 15, label: '手机号码', trigger: ['blur', 'change'] }],
        idcard: [{ required: false, validator: customValidator, min: 0, max: 18, label: '身份证号', trigger: ['blur', 'change'] }],
        email: [{ required: false, validator: customValidator, min: 0, max: 50, label: '邮箱', trigger: ['blur', 'change'] }],
        organizationId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '所属组织架构', trigger: ['blur', 'change'] }],
        rank: [{ required: true, validator: customValidator, min: 0, max: 20, label: '职级', trigger: ['blur', 'change'] }],
      },
      roleCheckedList: [],
      organizationList: initListStore().organizationList,
      roleList: initListStore().roleList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.getList()
    // this.initList()
  },
  methods: {
    getListPageSize,
    // async initList() {
    //   let p1 = doGet(this.svc, '/role/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2])
    //   this.roleList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    // },
    getList() {
      this.listLoading = true
      this.listQuery.lastLoginTimeStart = ''
      this.listQuery.lastLoginTimeEnd = ''
      if (this.listQuery.lastLoginTimeRange) {
        this.listQuery.lastLoginTimeStart = this.listQuery.lastLoginTimeRange[0]
        this.listQuery.lastLoginTimeEnd = this.listQuery.lastLoginTimeRange[1]
      }
      doGet(this.svc, '/customUser/queryUser', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
      this.listQuery.lastLoginTimeStart = ''
      this.listQuery.lastLoginTimeEnd = ''
      this.listQuery.lastLoginTimeRange = []
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row) {
      doPut(this.svc, '/user/modify', row, false).then(() => {
        notifySuccess('操作成功')
        this.getList()
      })
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      doGet(this.svc, '/user-role/page', {userId: row.id, pageSize: getListPageSize()}, false).then(res => {
        this.roleCheckedList = []
        res['records'].map(item => {
          this.roleCheckedList.push(item.roleId)
        })
        this.dialogType = 'edit'
        this.dialogTypeTitle = '编辑'
        this.dialogVisible = true
        this.checkStrictly = true
        this.obj = Object.assign({}, row)
      })
    },
    handleView(row) {
      doGet(this.svc, '/user-role/page', {userId: row.id, pageSize: getListPageSize()}, false).then(res => {
        this.roleCheckedList = []
        res['records'].map(item => {
          this.roleCheckedList.push(item.roleId)
        })
        this.dialogType = 'view'
        this.dialogTypeTitle = '详情'
        this.dialogVisible = true
        this.checkStrictly = false
        this.obj = Object.assign({}, row)
      })
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/user/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, '/user/' + row.id, {}).then(() => {
        notifySuccess('操作成功')
        this.getList()
        initListUpdate('userList', '/user/page')
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.obj
      o.roles = []
      this.roleCheckedList.map(item => {
        o.roles.push({roleId: item})
      })
      doPost(this.svc, '/custom/saveUser', o).then(() => {
        notifySuccess('操作成功')
        this.getList()
        initListUpdate('userList', '/user/page')
        this.dialogVisible = false
        this.roleCheckedList = []
      })
    },
  }
}
</script>
